// 购物车状态
import { insertCart, findCartList, deleteCart, updateCart, checkAllCart } from '@/api/Cart'
import { Message } from '@/components/Message'
export default {
  namespaced: true,
  state: () => ({
    list: []
  }),
  mutations: {
    setList (state, list) {
      state.list = list
    },
    cler (state, val) {
      state.list = []
    }
  },
  getters: {
    effectiveList (state) {
      return state.list.filter(itm => itm.isEffective)
    },
    allCount (state, getters) {
      return getters.effectiveList.reduce((a, c) => a + c.count, 0)
    },
    allPrice (state, getters) {
      return getters.effectiveList.reduce((a, c) => a + c.count * c.nowPrice, 0)
    },
    selectCart (state, getters) {
      return getters.effectiveList.filter(itm => itm.selected).reduce((a, c) => a + c.count, 0)
    },
    sumCart (state, getters) {
      return getters.effectiveList.filter(itm => itm.selected).reduce((a, c) => a + c.count * c.nowPrice, 0)
    },
    addCart (state, getters) {
      return getters.effectiveList.every(itm => itm.selected)
    }
  },
  actions: {
    asyncInsertCart (ctx, obj) {
      return new Promise((resolve, reject) => {
        insertCart({ ...obj }).then(() => {
          findCartList().then(res => {
            ctx.commit('setList', res.result)
            resolve()
          })
        }).catch(() => {
          Message({ type: 'error', text: '请选择规格,颜色,数量' })
        })
      })
    },
    delCart (ctx, ids) {
      return new Promise((resolve, reject) => {
        deleteCart(ids).then(() => {
          findCartList().then(res => {
            ctx.commit('setList', res.result)
            resolve()
          })
        })
      })
    },
    getFind (ctx) {
      findCartList().then(res => {
        ctx.commit('setList', res.result)
      })
    },
    // 单选
    singleCheck (ctx, { i, show }) {
      updateCart({ skuId: i.skuId, selected: show, count: i.count }).then(() => {
        findCartList().then(res => {
          ctx.commit('setList', res.result)
        })
      })
    },
    // 全选
    checkAllCart (ctx, show) {
      const res = ctx.getters.effectiveList.map(itm => itm.skuId)
      checkAllCart({ selected: show, ids: res }).then(() => {
        findCartList().then(res => {
          ctx.commit('setList', res.result)
        })
      })
    },
    numCart (ctx, { i, show }) {
      updateCart({ skuId: i.skuId, selected: i.selected, count: show }).then(() => {
        findCartList().then(res => {
          ctx.commit('setList', res.result)
        })
      })
    }
  }
}
